package com.small.springframework.beans.factory.support;


import cn.hutool.core.bean.BeanUtil;
import com.small.springframework.beans.BeansException;
import com.small.springframework.beans.PropertyValue;
import com.small.springframework.beans.PropertyValues;
import com.small.springframework.beans.factory.config.BeanDefinition;
import com.small.springframework.beans.factory.config.BeanReference;

import java.lang.reflect.Constructor;

public abstract class AbstractAutowireCapableBeanFactory extends AbstractBeanFactory{

    InstantiationStrategy instantiation = new CglibSubclassingInstantiationStrategy();

    @Override
    protected Object createBean(String beanName, BeanDefinition beanDefinition,Object[] args) throws BeansException {
        Object bean = null;
        try {
            bean = createInstanceBean(beanName,beanDefinition,args);

            applyPropertyValues(beanName,bean,beanDefinition);

        } catch (Exception e) {
            throw new BeansException("Instantiation of bean failed", e);
        }

        addSingleton(beanName, bean);
        return bean;
    }

    private void applyPropertyValues(String beanName, Object bean, BeanDefinition beanDefinition) {
        try {

            PropertyValues propertyValues = beanDefinition.getPropertyValues();
            if (propertyValues != null){
                for (PropertyValue property:propertyValues.getPropertyValues()) {
                    String name = property.getName();
                    Object value = property.getValue();
                    //解决循环依赖
                    if (value instanceof BeanReference) {
                        // A 依赖 B，获取 B 的实例化
                        BeanReference beanReference = (BeanReference) value;
                        value = getBean(beanReference.getBeanName());
                    }
                    // 属性填充
                    BeanUtil.setFieldValue(bean, name, value);
                }
            }
        }catch (Exception e){
            throw new BeansException("Error setting property values：" + beanName);
        }

    }


    private Object createInstanceBean(String beanName, BeanDefinition beanDefinition,Object[] args) {

        Class beanClass = beanDefinition.getBeanClass();
        Constructor[] declaredConstructors = beanClass.getDeclaredConstructors();
        Constructor constructor = null;
        for (Constructor ctr:declaredConstructors) {
            if (args != null && args.length == ctr.getParameterTypes().length){
                constructor = ctr;
                break;
            }
        }

        return getInstantiation().instantiate(beanDefinition,beanName,constructor,args);
    }

    private InstantiationStrategy getInstantiation() {
        return instantiation;
    }

}
